﻿using Microsoft.IdentityModel.Tokens;
using Rj.PersonnelVerification.Server.DataBaseContext.Entities;
using Rj.PersonnelVerification.Server.Repositories;
using Rj.PersonnelVerification.Server.Utils;
using Rj.PersonnelVerification.Shared.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Rj.PersonnelVerification.Server.Servers.Impl
{
    public class AuthService: IAuthService
    {
        private IHisRepository HisRepository;
        private IConfiguration Configuration;

        public AuthService(IHisRepository hisRepository, IConfiguration configuration)
        {
            HisRepository = hisRepository;
            Configuration = configuration;
        }

        public bool Login(LoginModel model,out string token)
        {

            var tbWorker= HisRepository.QueryByExample<SystemTbWorker>(s => s.WorkerNo == model.UserName).FirstOrDefault();
            if(tbWorker==null)
            {
                token = "用户名错误!";
                return false;
            }
            var tbUser= HisRepository.QueryByExample<TbUser>(u=>u.Workerid== tbWorker.WorkerId).FirstOrDefault();
            if (tbUser == null)
            {
                token = "用户名错误!";
                return false;
            }
            var pwd = CryptoHelper.MD5Encrypt(model.Pwd);
            if (tbUser.Password != pwd)
            {
                token = "密码错误!";
                return false;
            }

            token = GenerateJwtToken(model.UserName);
            return true;
        }
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private string GenerateJwtToken(string username)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "Client",
                audience: "Client",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
